package com.wust.task;

import java.util.ArrayList;
import java.util.List;

import com.wust.database.DatabaseFactory;
import com.wust.util.ConstDefine;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class TaskDao {
	private Context context;
	private List<Task>tasklist;
	public TaskDao(Context context)
	{
		this.context=context;
	}
	public void insertTask(Task task)
	{
		DatabaseFactory database=new DatabaseFactory(context,ConstDefine.DatabaseFactoryUtil.DATABASE_NAME);
		SQLiteDatabase db=database.getWritableDatabase();
		ContentValues value=new ContentValues();
		value.put("date1", task.getDate1());
		value.put("time1", task.getTime1());
		value.put("alarm", task.getAlarm());
		value.put("on_off", task.getOn_off());
		value.put("created", task.getCreated());
		db.insert(ConstDefine.Tasks.TASK_LIST_TABLE_NAME, null, value);
		db.close();
	}
	public List<Task> queryTasks()
	{
		DatabaseFactory database=new DatabaseFactory(context,ConstDefine.DatabaseFactoryUtil.DATABASE_NAME);
		SQLiteDatabase db=database.getReadableDatabase();
		Cursor cursor=db.query(ConstDefine.Tasks.TASK_LIST_TABLE_NAME, null,null,null, null, null, null);
		tasklist=new ArrayList<Task>();
		while(cursor.moveToNext())
		{
			Task task=new Task();
			task.setId(cursor.getInt(cursor.getColumnIndex("id")));
			task.setDate1(cursor.getString(cursor.getColumnIndex("date1")));
			task.setTime1(cursor.getString(cursor.getColumnIndex("time1")));
			task.setOn_off(cursor.getInt(cursor.getColumnIndex("on_off")));
			task.setAlarm(cursor.getInt(cursor.getColumnIndex("alarm")));
			task.setCreated(cursor.getString(cursor.getColumnIndex("created")));
			tasklist.add(task);
		}
		db.close();
		return tasklist;
	}
	public Task getTask(String id)
	{
		DatabaseFactory database=new DatabaseFactory(context,ConstDefine.DatabaseFactoryUtil.DATABASE_NAME);
		SQLiteDatabase db=database.getReadableDatabase();
		Cursor cursor=db.query(ConstDefine.Tasks.TASK_LIST_TABLE_NAME, null,"id=?",new String[]{id}, null, null, null);
		Task task=new Task();
		while(cursor.moveToNext())
		{
			
			task.setId(cursor.getInt(cursor.getColumnIndex("id")));
			task.setDate1(cursor.getString(cursor.getColumnIndex("date1")));
			task.setTime1(cursor.getString(cursor.getColumnIndex("time1")));
			task.setOn_off(cursor.getInt(cursor.getColumnIndex("on_off")));
			task.setAlarm(cursor.getInt(cursor.getColumnIndex("alarm")));
			task.setCreated(cursor.getString(cursor.getColumnIndex("created")));
			
		}
		db.close();
		return task;
	}
	public void deleteTask(String id)
	{
		DatabaseFactory database=new DatabaseFactory(context,ConstDefine.DatabaseFactoryUtil.DATABASE_NAME);
		SQLiteDatabase db=database.getWritableDatabase();
		db.delete(ConstDefine.Tasks.TASK_LIST_TABLE_NAME, "id=?",new String[]{id});
		db.close();
	}
}
